const express = require("express");
const fs = require('fs');
const multer  = require('multer');
// 一个解析文件上传的插件
// 提供文件上传的对象
const upload = multer({})
// const upload = multer({dest:'./img'})
const router = express.Router();
// upload.single("hehe") 单文件上传 key 为 hehe

/**
 * @api {post} /file/upload 文件上传
 * @apiName /file/upload
 * @apiGroup file
 *
 * @apiParam {Object} hehe 文件的formdata对象.
 *
 * @apiSuccess {String} msg  信息.
 * @apiSuccess {String} code 状态码.
 * @apiSuccess {String} path 上传文件的路径.
 */


router.post("/upload",upload.single("hehe"),async (req,res) => {
  // req.file 包含文件上传信息
  console.log(req.file)
  const {mimetype,buffer,size} = req.file;
  // 通过size 进行尺寸验证
  if(size >= 1000 * 1024) {
    return res.send({code:-1,msg: "超过最大限制"})
  }
  // 通过mimetype 做类型验证
  const type = mimetype.split("/")[1];
  const limitArr = ["png","jpg","jpeg"]
  if(!limitArr.includes(type)) {
    return res.send({code:-2,msg: "文件类型错误"})
  }
  // 将文件上传信息写入到服务器
  const fileName = (new Date()).getTime() + Math.random() * 99999 + "." + type
  const path = `http://192.168.52.138:3000/hehe/${fileName}`
  fs.writeFileSync(`./img/${fileName}`,buffer)  
  res.send({ msg: "图片上传成功", code: 0,path})
})


module.exports = router
